package com.file.parser;

import com.file.bo.NCBDC;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 南昌不动产pdf解析
 * @author anyspa
 */

@Slf4j
public class NCBDCPdfParser extends BasePdfParser {

    public ResponseData<String> parseNCBDCPdfToJson(String daId, String filePath) {
        log.info("parseNCBDCPdfToJson started, daId:{}", daId);
        String json;

        try {
            List<NCBDC> ncbdcList = parseNCBDCPdf(filePath);
            json = JsonUtils.convertObjectToJson(ncbdcList);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseNCBDCPdfToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseNCBDCPdfToJson completed, daId:{}", daId);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private List<NCBDC> parseNCBDCPdf(String filePath) {
        List<NCBDC> ncbdcList = new ArrayList<>();

        boolean hasNCBDCData = hasNCBDCData(filePath);
        if (hasNCBDCData) {

            try {
                Integer pageNumber = getPdfPageNumber(filePath);
                // 默认每一页一套房
                for (int i = 1; i <= pageNumber; i++) {
                    String pageText = parsePdfPageTextByPageNumber(filePath, i);
                    // 南昌不动产一个pdf文件可能会包含多个不动产
                    if (pageText.contains("受理编号")) {
                        NCBDC ncbdc = parsePdfHeader(pageText);
                        List<NCBDC.MortgageInfo> mortgageInfoList = new ArrayList<>();
                        List<NCBDC.SealUpInfo> sealUpInfoList = new ArrayList<>();

                        String obligee = pageText.substring(pageText.indexOf("权利人") + 3, pageText.indexOf("证件号码")).trim();
                        String idNo = pageText.substring(pageText.indexOf("证件号码") + 4, pageText.indexOf("不动产权证号")).trim();
                        String realEstateOwnershipCertificateNo = pageText.substring(pageText.indexOf("不动产权证号") + 6, pageText.indexOf("不动产单元号")).trim();
                        String realEstateUnitNo = pageText.substring(pageText.indexOf("不动产单元号") + 6, pageText.indexOf("土地证号")).trim();
                        String landCertificateNo = pageText.substring(pageText.indexOf("土地证号") + 4, pageText.indexOf("状态")).trim();
                        String status = pageText.substring(pageText.indexOf("状态") + 2, pageText.indexOf("登记时间")).trim();
                        String registrationDate = pageText.substring(pageText.indexOf("登记时间") + 4, pageText.indexOf("权利类型")).trim();
                        String rightType = pageText.substring(pageText.indexOf("权利类型") + 4, pageText.indexOf("权利性质")).trim();
                        String natureOfRights = pageText.substring(pageText.indexOf("权利性质") + 4, pageText.indexOf("不动产面积（m²）")).trim();
                        String area = pageText.substring(pageText.indexOf("不动产面积（m²）") + 9, pageText.indexOf("用途")).trim();
                        String use = pageText.substring(pageText.indexOf("用途") + 2, pageText.indexOf("共有情况")).trim();
                        String coOwnership = pageText.substring(pageText.indexOf("共有情况") + 4, pageText.indexOf("使用期限（年）")).trim();
                        String serviceLife = pageText.substring(pageText.indexOf("使用期限（年）") + 7, pageText.indexOf("坐落")).trim();
                        String location = pageText.substring(pageText.indexOf("坐落") + 2, pageText.indexOf("附记")).trim();
                        String supplement = pageText.substring(pageText.indexOf("附记") + 2, pageText.indexOf("序号抵押权人")).trim();
                        ncbdc.setObligee(obligee);
                        ncbdc.setIdNo(idNo);
                        ncbdc.setRealEstateOwnershipCertificateNo(realEstateOwnershipCertificateNo);
                        ncbdc.setRealEstateUnitNo(realEstateUnitNo);
                        ncbdc.setLandCertificateNo(landCertificateNo);
                        ncbdc.setStatus(status);
                        ncbdc.setRegistrationDate(registrationDate);
                        ncbdc.setRightType(rightType);
                        ncbdc.setNatureOfRights(natureOfRights);
                        ncbdc.setArea(area);
                        ncbdc.setUse(use);
                        ncbdc.setCoOwnership(coOwnership);
                        ncbdc.setServiceLife(serviceLife);
                        ncbdc.setLocation(location);
                        ncbdc.setSupplement(supplement);

                        // 抵押信息
                        String mortgageInfoText = pageText.substring(pageText.indexOf("序号抵押权人"), pageText.indexOf("序号查封机关"));
                        String mortgageInfoRecordText = mortgageInfoText.substring(mortgageInfoText.indexOf("登记时间") + 4);
                        if (StringUtils.isBlank(mortgageInfoRecordText) || mortgageInfoRecordText.trim().equals("无")) {
                            NCBDC.MortgageInfo mortgageInfo = new NCBDC.MortgageInfo();
                            mortgageInfoList.add(mortgageInfo);
                        } else {
                            // 1中国民生银行股份有限公司南昌分行赣(2022)南昌市不动产证明第7000000号750000元 2022-01-24 2032-01-24 10 2022-01-28
                            Pattern pattern = Pattern.compile("\\d{1}\\s?\\S{2,60}\\s?\\d{3,8}元\\s?\\d{4}-\\d{2}-\\d{2}\\s?\\d{4}-\\d{2}-\\d{2}\\s?\\d{1,2}\\s?\\d{4}-\\d{2}-\\d{2}");
                            Matcher matcher = pattern.matcher(mortgageInfoRecordText.trim());
                            while (matcher.find()) {
                                NCBDC.MortgageInfo mortgageInfo = new NCBDC.MortgageInfo();
                                String group = matcher.group();
                                Pattern serialNoPattern = Pattern.compile("\\d{1}");
                                Matcher serialNoMatcher = serialNoPattern.matcher(group);
                                if (serialNoMatcher.find()) {
                                    mortgageInfo.setSerialNo(serialNoMatcher.group());
                                }

                                if (StringUtils.isNotBlank(mortgageInfo.getSerialNo())) {
                                    String mortgagee = group.substring(group.indexOf(mortgageInfo.getSerialNo()) + mortgageInfo.getSerialNo().length(),
                                            group.indexOf("赣(20"));
                                    mortgageInfo.setMortgagee(mortgagee);
                                }

                                Pattern mortgageAmountPattern = Pattern.compile("\\d{3,8}元");
                                Matcher mortgageAmountMatcher = mortgageAmountPattern.matcher(group);
                                if (mortgageAmountMatcher.find()) {
                                    mortgageInfo.setMortgageAmount(mortgageAmountMatcher.group());
                                }

                                if (StringUtils.isNoneBlank(mortgageInfo.getMortgageAmount(), mortgageInfo.getMortgagee())) {
                                    String realEstateCertificateNo = group.substring(group.indexOf(mortgageInfo.getMortgagee())
                                            + mortgageInfo.getMortgagee().length(), group.indexOf(mortgageInfo.getMortgageAmount()));
                                    mortgageInfo.setRealEstateCertificateNo(realEstateCertificateNo);

                                    String lastFourCol = group.substring(group.indexOf(mortgageInfo.getMortgageAmount()) + mortgageInfo.getMortgageAmount().length());
                                    List<String> list = Splitter.on(" ").splitToList(lastFourCol.trim());
                                    if (list.size() == 4) {
                                        mortgageInfo.setRightStartDate(list.get(0));
                                        mortgageInfo.setRightEndDate(list.get(1));
                                        mortgageInfo.setMortgagePeriod(list.get(2));
                                        mortgageInfo.setRegistrationDate(list.get(3));
                                    }
                                }
                                mortgageInfoList.add(mortgageInfo);
                            }
                        }
                        ncbdc.setMortgageInfoList(mortgageInfoList);

                        // 查封信息
                        String sealUpInfoText = pageText.substring(pageText.indexOf("序号查封机关"), pageText.indexOf("备注：1、上述查询结果"));
                        String sealUpInfoRecordText = sealUpInfoText.substring(sealUpInfoText.indexOf("送达时间") + 4).trim();
                        if (StringUtils.isBlank(sealUpInfoRecordText) || sealUpInfoRecordText.equals("无")) {
                            NCBDC.SealUpInfo sealUpInfo = new NCBDC.SealUpInfo();
                            sealUpInfoList.add(sealUpInfo);
                        } else {
                            // 查封信息暂时没有案例，无法做解析
                        }
                        ncbdc.setSealUpInfoList(sealUpInfoList);
                        ncbdcList.add(ncbdc);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            // 无房
            String pageText = parsePdfHeaderText2(filePath);
            NCBDC ncbdc = parsePdfHeader(pageText);

            List<NCBDC.MortgageInfo> mortgageInfoList = new ArrayList<>();
            mortgageInfoList.add(new NCBDC.MortgageInfo());
            ncbdc.setMortgageInfoList(mortgageInfoList);

            List<NCBDC.SealUpInfo> sealUpInfoList = new ArrayList<>();
            sealUpInfoList.add(new NCBDC.SealUpInfo());
            ncbdc.setSealUpInfoList(sealUpInfoList);
            ncbdcList.add(ncbdc);
        }

        return ncbdcList;
    }

    private NCBDC parsePdfHeader(String pageText) {
        NCBDC ncbdc = new NCBDC();
        // 南昌市不动产登记信息网络查询结果受理编号： ZC202210270482使用账号：张三 查询时间：2022-10-28 09:17:11
        String acceptNo = "";
        if (pageText.contains("受理编号：")) {
            acceptNo = pageText.substring(pageText.indexOf("受理编号：") + 5, pageText.indexOf("使用账号")).trim();
        } else if (pageText.contains("受理编号:")){
            acceptNo = pageText.substring(pageText.indexOf("受理编号:") + 5, pageText.indexOf("使用账号")).trim();
        }

        String account = "";
        if (pageText.contains("使用账号：")) {
            account = pageText.substring(pageText.indexOf("使用账号：") + 5, pageText.indexOf("查询时间")).trim();
        } else if (pageText.contains("使用账号:")){
            acceptNo = pageText.substring(pageText.indexOf("使用账号:") + 5, pageText.indexOf("查询时间")).trim();
        }

        String queryDate = "";
        if (pageText.contains("查询时间：")) {
            queryDate = pageText.substring(pageText.indexOf("查询时间：") + 5, pageText.indexOf("按照")).trim();
        } else if (pageText.contains("查询时间:")){
            queryDate = pageText.substring(pageText.indexOf("查询时间:") + 5, pageText.indexOf("按照")).trim();
        }

        ncbdc.setAcceptNo(acceptNo);
        ncbdc.setAccount(account);
        ncbdc.setQueryDate(queryDate);
        return ncbdc;
    }

    public boolean hasNCBDCData(String filePath) {
        // 按照查询申请人张三(身份证：100000000000001)提出的查询申请，截至2022年10月28日，根据查询申请人名称及证件号码在南昌市不动产登记服务平台内查询，未查询到不动产登记信息。
        String text = parsePdfHeaderText2(filePath);
        return !text.contains("未查询到不动产登记信息");
    }

    public static void main(String[] args) {
        NCBDCPdfParser ncbdcPdfParser = new NCBDCPdfParser();
        String json = ncbdcPdfParser.parseNCBDCPdfToJson("", "D:\\data\\files\\NCBDC\\zddbcvaq1616335796334477312_90477f103285fc212d0738d07f07ea85_chrome-ncsbdc-bdc_bdcsj.pdf").getData();
        System.out.println(json);

        json = ncbdcPdfParser.parseNCBDCPdfToJson("", "D:\\data\\files\\NCBDC\\zddbcvaq1615988222675107840_aee0986b3615738643d4d9cdc73cde9d_chrome-ncsbdc-bdc_bdcsj.pdf").getData();
        System.out.println(json);

        json = ncbdcPdfParser.parseNCBDCPdfToJson("", "D:\\data\\files\\NCBDC\\zddbcvaq1619515383386193920_0610b2758c03abb3ab82e3fb142c2df4_chrome-ncsbdc-bdc_bdcsj.pdf").getData();
        System.out.println(json);

        // 无房
        json = ncbdcPdfParser.parseNCBDCPdfToJson("", "D:\\data\\files\\NCBDC\\chrome-ncbdc_bdcsj.pdf").getData();
        System.out.println(json);
    }
}
